import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse, AxiosError } from 'axios'
import { errorMsg } from './message'
import { getToken } from './session'

// 处理 类型“AxiosResponse<any, any>”上不存在属性 “xxx”
declare module 'axios' {
  interface AxiosInstance {
    (config: AxiosRequestConfig): Promise<any>
  }
}

const service = axios.create({
  timeout: 60 * 1000
})

service.interceptors.request.use((config: AxiosRequestConfig) => {
  const headers = <AxiosRequestHeaders>config.headers
  headers['Authorization'] = 'Bearer ' + getToken()
  return config
})

service.interceptors.response.use((response: AxiosResponse) => {
  const data = response.data
  if (data.code === 200) {
    return data
  } else {
    return Promise.reject(data.message)
  }
}, (error: AxiosError) => {
  const msg = error.message
  errorMsg(msg)
  return Promise.reject(msg)
})

export default service
